<template>
  <div class="language-selector relative">
    <button
      :class="[
        'flex items-center px-3 py-2 rounded-lg text-sm font-medium transition-colors',
        'bg-background hover:bg-muted border border-border',
        'focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2'
      ]"
      @click="showDropdown = !showDropdown">
      <span class="mr-2">{{ currentLocaleInfo.name }}</span>
      <i :class="['i-mdi-chevron-down w-4 h-4 transition-transform', showDropdown && 'rotate-180']" />
    </button>

    <!-- 下拉菜单 -->
    <div
      v-if="showDropdown"
      class="absolute top-full right-0 mt-1 w-48 bg-popover border border-border rounded-lg shadow-lg z-50">
      <div class="py-1">
        <button
          v-for="locale in SUPPORTED_LOCALES"
          :key="locale.code"
          :class="[
            'w-full flex items-center px-3 py-2 text-sm transition-colors text-left',
            'hover:bg-muted',
            currentLocaleRef === locale.code ? 'bg-primary/10 text-primary' : 'text-foreground'
          ]"
          @click="selectLanguage(locale.code)">
          <span class="mr-3 text-lg">{{ locale.flag }}</span>
          <span>{{ locale.name }}</span>
          <i v-if="currentLocaleRef === locale.code" class="i-mdi-check w-4 h-4 ml-auto text-primary" />
        </button>
      </div>
    </div>

    <!-- 点击外部关闭下拉菜单 -->
    <div v-if="showDropdown" class="fixed inset-0 z-40" @click="showDropdown = false"></div>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue';

import { currentLocaleRef, setLocale, SUPPORTED_LOCALES, type SupportedLocale } from '@/i18n';

const showDropdown = ref(false);

// 当前语言信息 - 直接使用响应式引用
const currentLocaleInfo = computed(() => {
  const current = currentLocaleRef.value;
  console.log('当前语言:', current);

  const found = SUPPORTED_LOCALES.find((l) => l.code === current);

  if (!found) {
    console.warn('未找到匹配的语言配置，使用默认配置');
  }

  return found || SUPPORTED_LOCALES[0];
});

// 选择语言
const selectLanguage = async (localeCode: SupportedLocale) => {
  console.log('选择语言:', localeCode);
  setLocale(localeCode);
  showDropdown.value = false;

  // 等待下一个tick，确保响应式更新完成
  await nextTick();
  console.log('语言选择完成，当前语言:', currentLocaleRef.value);
};

// 点击外部关闭下拉菜单
const handleClickOutside = (event: MouseEvent) => {
  const target = event.target as Element;
  if (!target.closest('.language-selector')) {
    showDropdown.value = false;
  }
};

onMounted(() => {
  document.addEventListener('click', handleClickOutside);
});

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside);
});
</script>

<style lang="scss" scoped></style>
